package com.example.socket.socket.simpledemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        final int DEFAUT_PORT=8888;

        ServerSocket serverSocket=null;

        try {
            serverSocket=new ServerSocket(DEFAUT_PORT);
            System.out.println("启动服务监听端口："+DEFAUT_PORT);
            while (true){
                Socket socket=serverSocket.accept();
                BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                String msg = reader.readLine();
                if(msg!=null){
                    System.out.println("客户端{"+socket.getPort()+"}"+msg);
                    //回复客户发送的消息
                    bufferedWriter.write("服务器 ：贱人"+"\n");
                    bufferedWriter.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
